/**
 * @create 2022-10-22
 * @desc index
 */
const fs = require('fs');
const gogocode = require('gogocode');

const getSourceCode = () => {
    return fs.readFileSync('./source.tsx', 'utf-8');
}
const outputFn = (code) => {
    fs.writeFileSync('./dist/index.tsx', code);
}

const getAllImport = (gogoAst) => {
    return gogoAst.find([
        `import $_$def from "$_$path"`,
        `import { $_$sourceKey as $_$curKey } from "$_$path"`,
        `import * as $_$allKey  from "$_$path"`
    ])
}
const addImportAtLast = (gogoAst, importStr) => {
    const allImport = getAllImport(gogoAst);
    const lastImport = allImport[allImport.length - 1];

    if (lastImport) {
        gogocode(lastImport.nodePath).after(importStr + '\n');
    }
}

const changeButton = (gogoAst) => {
    gogoAst.replace(`import {B1, $$$0} from "b";`,
        `import ButtonGroup, {ButtonGroupList} from 'button-group';\n`);

    gogoAst.find('B1')
        .each(item => item.parent().node.type === 'TSTypeReference')
        .each(item => item.replaceBy('ButtonGroupList'));

    gogoAst.find('<BComp list={list}/>')
        .each(item => item.replaceBy('<ButtonGroup list={list}/>'));
}

const addAttr = (gogoAst) => {
    addImportAtLast(gogoAst, `import conoleFn from "console-fn";`);

    const appAst = gogoAst.find(`const App = () => {$$$0}`);

    // 插入 sayName 函数
    if (appAst.length) {

        // 箭头函数的 body 节点藏的比较深
        const declarations = gogocode(appAst.attr('declarations')[0]).attr('init');
        gogocode(declarations).prepend('body',
            `const sayName = (name) => conoleFn(name);`)
    }

    gogoAst.replace(`{visiable: $_$1, $$$0}`, `{visible: $_$1, $$$0}`);
    gogoAst.replace(`{title: $_$1, $$$0}`, `{name: $_$1, $$$0}`);

    // 给 jsx 加属性
    gogoAst.replace(`<ButtonGroup $$$1 />`, `<ButtonGroup onClick={sayName} $$$1 />`);
}

const start = () => {
    const sourceCode = getSourceCode();
    const gogoAst = gogocode(sourceCode);

    changeButton(gogoAst);
    addAttr(gogoAst);

    outputFn(gogoAst.generate())
}

start()